Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
Django >= 3.1 and is_ajax

HttpRequest.is_ajax() is deprecated starting with version 3.1.

I want to return html if the page is requested from a browser and as JsonResponse if called from javascript or programmatically.

I am seeking guidance on how to do that.

https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpRequest.is_ajax

over 4 years ago · Santiago Trujillo
7 Respostas
Responde à pergunta

0

I did what arakkal-abu said but I also added 'X-Requested-With' header with the same value ie. 'XMLHttpRequest'

to my request and it worked

over 4 years ago · Santiago Trujillo Relatório

0

Make sure to import this at the top

import re
from django.http import JsonResponse
from django.utils.translation import gettext_lazy as _
from django.conf.urls import handler404

You can have this inside your function/method to determine if from browser or ajax call

    requested_html = re.search(r'^text/html', request.META.get('HTTP_ACCEPT'))
    if requested_html:
        # requested from browser, do as per your wish
    # ajax call. Returning as per wish 
    return JsonResponse({
        'detail': _('Requested API URL not found')
    }, status=404, safe=False)

Explanation

If you request to load a page from a browser, you would see in the network tab under the requested headers of that request, text/html is at the beginning of requested headers. enter image description here

However, if you are making an ajax call from the browser, the requested headers has */* in the beginning. If you attach

Accept: application/json

in the header, then requested headers become this enter image description here

From this, you can understand how the accept header is different in these cases.

over 4 years ago · Santiago Trujillo Relatório

0

have you tried to check HttpRequest.headers?
HttpRequest.is_ajax() depends on HTTP_X_REQUESTED_WITH header.
so you can check this header, if it is true it would be AJAX other wise it would be a request from a browser.

HttpRequest.headers['HTTP_X_REQUESTED_WITH']
over 4 years ago · Santiago Trujillo Relatório

0

Check HTTP_X_REQUESTED_WITH header

def sample_view(request):
    is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

From the Release Notes of 3.1

The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method, or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header.

over 4 years ago · Santiago Trujillo Relatório

0

Simply check the Content-Type header.

is_ajax = request.META.get("CONTENT_TYPE") == "application/json"
if is_ajax:
    do_stuff()
over 4 years ago · Santiago Trujillo Relatório

0

Funny thing -- the quoted deprecation blurb only gets you halfway there. There's no indication of how you "use the new HttpRequest.accepts method" to replace HttpRequest.is_ajax -- not in the deprecation text, nor the documentation, nor the release notes.

So, here it is: if request.accepts("application/json")

(At least that's what worked for me.)

over 4 years ago · Santiago Trujillo Relatório

0

Instead of:

if request.is_ajax():

Helped me:

if request.headers.get('x-requested-with') == 'XMLHttpRequest':
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda